package com.ylyq.ylxx.intercepter;

import com.ylyq.ylxx.constants.ExceptionEnum;
import com.ylyq.ylxx.context.FilterContextHandler;
import com.ylyq.ylxx.service.IJinritemaiOauthService;
import com.ylyq.ylxx.service.IOauthService;
import com.ylyq.ylxx.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 巨量拦截器
 */
@Slf4j
public class JinritemaiAuthIntercepter extends HandlerInterceptorAdapter {

    @Autowired
    private RedisUtil redisUtils;
    @Autowired
    private IJinritemaiOauthService iJinritemaiOauthService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        if(request.getMethod().equals(RequestMethod.OPTIONS.name()))
        {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }


        String access_token = (String) redisUtils.get("Jinritemai_access_token" + FilterContextHandler.getUserID());
        if (StringUtils.isBlank(access_token)) {
            String refresh_token = (String) redisUtils.get("Jinritemai_refresh_token" + FilterContextHandler.getUserID());
            if (StringUtils.isBlank(refresh_token)) {
                log.debug("refresh_token 过期：{}", refresh_token);
                outString(response,ExceptionEnum.AUTH_TOKEN_EXPIRE_LUBAN.getCode(), ExceptionEnum.AUTH_TOKEN_EXPIRE_LUBAN.getMsg());
                return false;
            }
            String accessToken = iJinritemaiOauthService.reFreshAccessToken(FilterContextHandler.getUserID(), refresh_token);
            FilterContextHandler.setLubanToken(accessToken);
        }else {
            FilterContextHandler.setLubanToken(access_token);
        }
        return super.preHandle(request, response, handler);
    }


    private void outString(HttpServletResponse response,int code,String str){
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setStatus(code);
            PrintWriter out = response.getWriter();
            out.print(str);
            log.info(str);
        } catch (Exception e) {
            log.error("写字符串异常");
        }
    }
}
